package com.sqlloader.db;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.impl.GenericObjectPool;
public class ConnectionPool {

	 private static ConnectionPool _instance;
	 private static PoolingDriver driver;
	 public static ConnectionPool getInstance()
	 {
	    if (_instance == null)
	      _instance = new ConnectionPool();
	    return _instance;
	 }
	 
	 private ConnectionPool()
	 {
		 try{
		      Class.forName("org.apache.commons.dbcp.PoolingDriver");
		      driver = (PoolingDriver)DriverManager.getDriver("jdbc:apache:commons:dbcp:");
		 } catch (ClassNotFoundException e) {
			 e.printStackTrace();
		 } catch (SQLException e) {
			 e.printStackTrace();
		 }
		 
		 
	 }
	 
   public void registerPool(String driverclassname,String username,String password,String url,String id)
	 {
		 try {
			Driver jdbcDriver = (Driver)Class.forName(driverclassname).newInstance();
			GenericObjectPool connectionPool = new GenericObjectPool(null, 10);
			connectionPool.setMaxIdle(10);
			Properties prop = new Properties();
		    prop.setProperty("user", username);
		    prop.setProperty("password", password);
		    ConnectionFactory connectionFactory = new DriverConnectionFactory(jdbcDriver, url, prop);
		    new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, null, true, -1, null, null);
		    driver.registerPool(id, connectionPool);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
	 }
	 
	 public Connection getConnection(String connectionId) throws SQLException
	 {
		 driver.getConnectionPool(connectionId);
		 Connection conn=driver.connect("jdbc:apache:commons:dbcp:"+connectionId, null);
		 return conn;
	 }
	 public void closePool(String connectionId) throws SQLException
	 {
	    driver.closePool(connectionId);
	 }
	 
	 public void closeAllPool() throws SQLException
	 {
	   	String[] poolNames = driver.getPoolNames();
	   	if(poolNames!=null&&poolNames.length>0)
	    for (int i = 0; i < poolNames.length; ++i) {
	      driver.closePool(poolNames[i]);
	    }
	 }
	 
	 public void clearPool(String connectionId) throws Exception {
		    driver.getConnectionPool(connectionId).clear();
	 }
	 
	 
	 
}
